<?php
require_once dirname(__FILE__) . '/common.inc.php';
require_once dirname(__FILE__) . "/DbUtils.class.php";
require_once dirname(__FILE__) . "/includes/MiscUtils.class.php";
require_once dirname(__FILE__) . "/libs/djpate/phpDocx.php";

$transaction_no = MiscUtils::getParam('i', NULL);
$template_plugin = 'invctmpl';
$myPdo = DbUtils::createPdoInst();

$cond_vals = new stdClass();
$cond_vals->c = 't.transaction_no = :v1';
$cond_vals->v = array(':v1' => $transaction_no);
$opts = new stdClass();
$opts->select_expr = 't.*, t1.family_name AS family_name, t1.first_name AS first_name, t1.phone AS phone, t1.mobile AS mobile, t1.email AS email, t1.fax AS fax, t1.address AS address, t1.company AS company';
$opts->join_expr = 'LEFT JOIN pz_sys_module_data_customer as t1 ON t.customer_id = t1.id';
$result = DbUtils::get($myPdo, 'pz_sys_module_data_transaction', $cond_vals, NULL, NULL, NULL, NULL, $opts);
if (count($result->d) != 1) {
  die('No Transaction Found');
}
$data = $result->d[0];
$cond_vals = new stdClass();
$cond_vals->c = 't.transaction_track_id = :v1';
$cond_vals->v = array(':v1' => $data->track_id);
$settles = DbUtils::get($myPdo, 'pz_sys_module_data_transaction_settle', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;

$sql = 'SHOW COLUMNS FROM pz_sys_module_data_transaction';
$stmt = $myPdo->prepare($sql);
$column_names = array();
$column_types = array();
try {
  if($stmt->execute()){
    $raw_column_data = $stmt->fetchAll();
    foreach($raw_column_data as $outer_key => $array){
      foreach($array as $inner_key => $value){
        if ($inner_key === 'Field'){
          if (!(int)$inner_key){
            $column_names[] = $value;
          }
        }
        if ($inner_key === 'Type'){
          if (!(int)$inner_key){
            $column_types[] = $value;
          }
        }
      }
    }
  }
} catch (Exception $e){
  die('Error occurs while accessing database');
}
$column_names[] = 'company';
$column_types[] = 'text';

$result = DbUtils::get($myPdo, 'pz_sys_plugin_' . $template_plugin . '_files', NULL, NULL, NULL, NULL, NULL, NULL);
if (count($result->d) != 1) {
  die('No Invoice Template');
}
$obj = $result->d[0];
$path = 'ext/plugin/bin/' . $template_plugin . '/uploads/' . $obj->name_on_server;

if (!file_exists($path)) {
  echo 'File not found in hard drive';
  exit;
} else {
  $not_good = '</w:t></w:r></w:p><w:p w:rsidRDefault="007F104F" w:rsidP="007F104F"><w:pPr><w:pBdr><w:top w:val="single" w:sz="4" w:space="1" w:color="auto"/><w:left w:val="single" w:sz="4" w:space="4" w:color="auto"/><w:bottom w:val="single" w:sz="4" w:space="1" w:color="auto"/><w:right w:val="single" w:sz="4" w:space="4" w:color="auto"/></w:pBdr><w:adjustRightInd w:val="0"/><w:snapToGrid w:val="0"/><w:spacing w:line="240" w:lineRule="auto"/><w:contextualSpacing/></w:pPr><w:r><w:t>';
  $phpdocx = new phpdocx($path);
  setlocale(LC_ALL, 'en_NZ');
  foreach ($column_names as $idx => &$column_name) {
    if (isset($column_types[$idx]) && $column_types[$idx] == 'datetime') {
      $data->$column_name = date('Y-m-d', strtotime($data->$column_name));
    }
//    if (isset($column_types[$idx]) && $column_types[$idx] == 'decimal(10,2)') {
//      $data->$column_name = str_replace('$', '', MiscUtils::money_format('%n', $data->$column_name));
//    } 
//    if ($column_name == 'fee_description') { 
//      $data->$column_name = str_replace('<br />', $not_good, nl2br($data->$column_name));
//    }
    $phpdocx->assign("#$column_name#", $data->$column_name);
  }
  if ($data->company == '') {
    $phpdocx->assign("Organisation:", '');
  }
  if ($data->fee_method == 'Deduct from settlement') {
    $phpdocx->assign("#_sell_amount#",  "$data->sell_amount - $data->fee_amount (Fee) = " . ($data->sell_amount - $data->fee_amount));
    $phpdocx->assign("#_fee#", '');
  } else {
    $phpdocx->assign("#_sell_amount#", $data->sell_amount);
    $phpdocx->assign("#_fee#", "Fee: $data->fee_currency_name $data->fee_amount");
  }
  $settle_txt = '';
  foreach ($settles as $idx => $settle) {
    if (count($settles) > 1) {
      if ($idx != 0) {
        $settle_txt .= $not_good . $not_good;
      }
    } else {
    }
    $settle_txt .= $settle->method . ' ';
    if ($data->fee_settle_track_id == $settle->track_id && $data->fee_method == 'Deduct from settlement') {
      $settle_txt .= $settle->amount - $data->fee_amount;
    } else {
      $settle_txt .= $settle->amount;
    }
    if ($settle->method == 'Bank Transfer') {
      $settle_txt .= $not_good;
      $settle_txt .= "Country/City: $settle->country/$settle->city$not_good" . "Bank Name/Branch: $settle->bank/$settle->branch$not_good" . "Account Name: $settle->account_name$not_good" . "Account Number: $settle->account_no$not_good" . "SWIFT Code: $settle->swift_code";
    }
  }
  $phpdocx->assign("#_settlements#", $settle_txt);
  $phpdocx->download("INVOICE$transaction_no.docx");
  exit;
}
?>